package com.ruoyi.common.utils.map;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
 * @author luobo
 * @title: MapLocalUtils
 * @projectName pos
 * @description: TODO
 * @date 2021-12-07 19:45:48
 */
@Component
public class MapLocalUtils {

    /**
     * map按照ASCII码排序
     * @param params 需要排序的map
     * @return
     */
    public static String createSortString(Map<String, String> params) {
        String sortString = "";
        if (CollectionUtil.isNotEmpty(params)) {
            sortString = params.entrySet().stream()
                    .filter(entity -> StrUtil.isNotBlank(entity.getKey()) && StrUtil.isNotBlank(entity.getValue()))
                    .sorted(Comparator.comparing(Map.Entry::getKey))
                    .map(entry -> entry.getKey() + "=" + entry.getValue())
                    .reduce((l, r) -> l + "&" + r)
                    .orElse("");
        }
        return sortString;
    }

    /**
     * java bean转map
     * @param bean
     * @return
     */
    public static Map<String, Object> beanToMap(Object bean) {
        Map<String, Object> map = new HashMap<>();
        BeanMap beanMap = BeanMap.create(bean);
        for (Object object : beanMap.entrySet()) {
            if (object instanceof Map.Entry) {
                Map.Entry<String , Object> entry = (Map.Entry<String, Object>)object ;
                String key = entry.getKey();
                map.put(key, beanMap.get(key));
            }
        }

        return map;
    }
}
